﻿using Autodesk.Revit.UI;
using Newtonsoft.Json.Linq;
using RevitMCPSDK.API.Base;
using RevitMCPSDK.API.Interfaces;
using RevitMCPSDK.API.Models.JsonRPC;
using RevitMCPSDK.API.Models.Results;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WpfLibrary1
{
    public class GetElementCommand : ExternalEventCommandBase
    {
        public GetElementCommand(IWaitableExternalEventHandler handler, UIApplication uiApp)
            : base(handler, uiApp)
        {
        }

        public override string CommandName => "GetElement";

        public override object Execute(JObject parameters, string requestId)
        {
            // Extract element ID from parameters
            if (!parameters.TryGetValue("elementId", out JToken elementIdToken))
                return CommandResult.CreateError("Missing elementId parameter");

            int elementId = elementIdToken.Value<int>();

            // Get the document
            var doc = UiApp.ActiveUIDocument.Document;

            // Find the element
            var element = doc.GetElement(new Autodesk.Revit.DB.ElementId(elementId));

            if (element == null)
                return CommandResult.CreateError($"Element with ID {elementId} not found",
                    new { ErrorCode = JsonRPCErrorCodes.ElementNotFound });

            // Return element information
            return CommandResult.CreateSuccess(new
            {
                Id = element.Id.IntegerValue,
                Name = element.Name,
                Category = element.Category?.Name
            });
        }
    }
}
